package com.example.benefitcommunity.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.example.benefitcommunity.dao.BcCommentDao;
import com.example.benefitcommunity.entity.*;
import com.example.benefitcommunity.dao.BcDynamicDao;
import com.example.benefitcommunity.enums.StatusCode;
import com.example.benefitcommunity.service.BcDynamicService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发表动态表(BcDynamic)表服务实现类
 *
 * @author makejava
 * @since 2025-08-27 16:38:36
 */
@Transactional(rollbackFor = Exception.class)
@Service("bcDynamicService")
public class BcDynamicServiceImpl implements BcDynamicService {
    @Resource
    private BcDynamicDao bcDynamicDao;

    @Resource
    private BcCommentDao bcCommentDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BcDynamic queryById(Integer id) {
        return this.bcDynamicDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param bcDynamic   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<BcDynamic> queryByPage(BcDynamic bcDynamic, PageRequest pageRequest) {
        long total = this.bcDynamicDao.count(bcDynamic);
        return new PageImpl<>(this.bcDynamicDao.queryAllByLimit(bcDynamic, pageRequest), pageRequest, total);
    }

    /**
     * @param type        筛选条件
     * @param communityid 筛选条件
     * @param pagenum     筛选条件
     * @param pagesize    筛选条件
     * @return
     */
    @Override
    public Result<Object> queryByDynamic(String type, Integer id, Integer communityid, Integer userid, Integer isshow, Integer pagenum, Integer pagesize) {
        PageHelper.startPage(pagenum, pagesize);
        BcDynamic bcDynamic = new BcDynamic();
        bcDynamic.setType(type);
        bcDynamic.setId(id);
        bcDynamic.setCommunityid(communityid);
        bcDynamic.setUserid(userid);
        bcDynamic.setIsshow(isshow);
        List<BcDynamic> list = this.bcDynamicDao.queryAll(bcDynamic);
        PageInfo<BcDynamic> pageInfo = new PageInfo<>(list);
        return new Result<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMsg(), pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 新增数据
     *
     * @param bcDynamic 实例对象
     * @return 实例对象
     */
    @Override
    public Result<Object> insert(BcDynamic bcDynamic) {
        List<BcDynamic> list = this.bcDynamicDao.queryAll(bcDynamic);
        if (list.isEmpty()) {
            if (this.bcDynamicDao.insert(bcDynamic) > 0) {
                return new Result<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMsg(), 1L, "发表动态新增成功！");
            }
            return new Result<>(StatusCode.ERROR.getCode(), StatusCode.ERROR.getMsg(), 0L, "发表动态新增失败！");
        }
        return new Result<>(StatusCode.ERROR.getCode(), StatusCode.ERROR.getMsg(), 0L, "发表动态已存在！");
    }

    /**
     * 修改数据
     *
     * @param bcDynamic 实例对象
     * @return 实例对象
     */
    @Override
    public BcDynamic update(BcDynamic bcDynamic) {
        this.bcDynamicDao.update(bcDynamic);
        return this.queryById(bcDynamic.getId());
    }

    /**
     * @param id 主键
     * @return
     */
    @Override
    public Result<Object> deleteById(Integer[] id) {
        int count = 0;
        //删除个别
        for (Integer i : id) {
            List<BcComment> list = this.bcCommentDao.queryById(i);
            //删除单个
            if (!list.isEmpty()) {
                //删除多个
                if (this.bcDynamicDao.deleteById(i) > 0) {
                    count++;
                }
            } else {
                //删除单个
                if (this.bcDynamicDao.deleteByIdOne(i) > 0) {
                    count++;
                }
            }
        }
        //判断删除结果
        if (count == id.length) {
            return new Result<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMsg(), (long) id.length, "发表动态删除成功！");
        }
        return new Result<>(StatusCode.ERROR.getCode(), StatusCode.ERROR.getMsg(), 0L, "发表动态删除失败！");
    }

    /**
     * @param BcDynamic
     * @return
     */
    @Override
    public Result<Object> like(BcDynamic bcDynamic) {
        int count = 0;
        BcDynamic bcDynamicNew = this.bcDynamicDao.queryById(bcDynamic.getId());
        if (bcDynamicNew != null) {
            // 假设 getReader() 应该返回 List<Integer>
            String result = JSONArray.toJSONString(bcDynamic.getReader());
            String result1 = (String) bcDynamicNew.getReader();
            List<Integer> list = JSONArray.parseArray(result, Integer.class);
            List<Integer> list1 = JSONArray.parseArray(result1, Integer.class);
            List<Integer> updatedReaders = new ArrayList<>();
            //判断集合是否为空
            if (list != null && !list.isEmpty() && list1 != null && !list1.isEmpty()) {
                //判断点赞数
                if (bcDynamicNew.getLikecount() < bcDynamic.getLikecount()) {
                    for (Integer readerId : list) {
                        // 可在此处添加具体业务逻辑
                        if (!list1.contains(readerId)) {
                            updatedReaders.add(readerId);
                            count++;
                        }
                    }
                    updatedReaders.addAll(list1);
                    //去重-顺序排序
//                    updatedReaders = updatedReaders.stream().distinct().sorted().collect(Collectors.toList());
                    bcDynamic.setLikecount(bcDynamicNew.getLikecount() + count);
                    bcDynamic.setReader(updatedReaders.toString());
                } else {
                    if (bcDynamicNew.getLikecount() == 0) {
                        return new Result<>(StatusCode.ERROR.getCode(), StatusCode.ERROR.getMsg(), 0L, "点赞数不能小于0！");
                    }
                    for (Integer readerId : list) {
                        // 可在此处添加具体业务逻辑
                        if (list1.contains(readerId)) {
                            list1.remove(readerId);
                            count++;
                        }
                    }
                    updatedReaders.addAll(list1);
                    bcDynamic.setLikecount(bcDynamicNew.getLikecount() - count);
                    bcDynamic.setReader(updatedReaders.toString());
                }

            } else {
                bcDynamic.setLikecount((bcDynamicNew.getLikecount() + 1));
                bcDynamic.setReader(list.toString());
            }
            if (this.bcDynamicDao.update(bcDynamic) > 0) {
                return new Result<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMsg(), 1L, "发表动态更新成功！");
            }
            return new Result<>(StatusCode.ERROR.getCode(), StatusCode.ERROR.getMsg(), 0L, "发表动态更新失败！");
        }
        return new Result<>(StatusCode.ERROR.getCode(), StatusCode.ERROR.getMsg(), 0L, "发表动态不存在！");
    }
}
